<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>nuxt | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="配套项目 概念优点    1、多页面    2、ssr seo 优化 每页有自己的tdk    3、页面的内容源码直接有了,vue源码是没有什么内容的,不利于抓取(预渲染，SSR优化) 预渲染    读取配置获取需要渲染的页面    发布模拟浏览器环境打开页面    页面脚本触发渲染时机    渲染出当前页面内容    获取渲染出的所有DOM结构    生成HTML文件   （模拟浏览器环境生成d">
<meta property="og:type" content="article">
<meta property="og:title" content="nuxt">
<meta property="og:url" content="http://example.com/2023/07/22/web/vue/vue-ssr-nuxt/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="配套项目 概念优点    1、多页面    2、ssr seo 优化 每页有自己的tdk    3、页面的内容源码直接有了,vue源码是没有什么内容的,不利于抓取(预渲染，SSR优化) 预渲染    读取配置获取需要渲染的页面    发布模拟浏览器环境打开页面    页面脚本触发渲染时机    渲染出当前页面内容    获取渲染出的所有DOM结构    生成HTML文件   （模拟浏览器环境生成d">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.696Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.696Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/web/vue/vue-ssr-nuxt/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'nuxt',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">nuxt</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.696Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.696Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="nuxt"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><a target="_blank" rel="noopener" href="https://github.com/liaozhongxun/lzo-nuxt-v2.0.git">配套项目</a></p>
<h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><p>优点<br>    1、多页面<br>    2、ssr seo 优化 每页有自己的tdk<br>    3、页面的内容源码直接有了,vue源码是没有什么内容的,不利于抓取(预渲染，SSR优化)</p>
<p>预渲染<br>    读取配置获取需要渲染的页面<br>    发布模拟浏览器环境打开页面<br>    页面脚本触发渲染时机<br>    渲染出当前页面内容<br>    获取渲染出的所有DOM结构<br>    生成HTML文件<br>   （模拟浏览器环境生成dom直接生成HTML文件，扔到页面上）<br>    vue seo方案 &#x3D;&gt; 预渲染: (得到打包后将数据生成到html源码的效果)<br>        1、使用预渲染插件 <code>prerender-spa-plugin</code><br>            配置中设置指定需要预渲染的页面<br>            无法配置动态路由<br>            不适合 token 权限的项目<br>        2、修改页面 TDK <code>vue-meta-info</code> （在每个页面组件中配置自己后面的 TDK 信息）<br>            接口数据无效<br>        <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="attr">metaInfo</span>:&#123;</span><br><span class="line">        <span class="attr">title</span>:<span class="string">&quot;xxx&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></p>
<p>服务端渲染(SSR)<br>    前端渲染的方式（C&#x2F;S）<br>        用户通过浏览器向服务端发送请求 -&gt; 服务端相应数据到看浏览器，vue将数据渲染到页面上<br>        拿到数据之前页面已经打开</p>
<pre><code>服务端渲染步骤 （C/S/S）
    用户发送请求到 Node Server -&gt; Node Server(可以用 Nuxt 做)将发送请求到后端 -&gt;  返回数据到 Node Server -&gt; 渲染好完整页面呈现给用户
    <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 打包</span></span><br><span class="line">npm build  (不会生成dist)</span><br><span class="line">npm generate  依据路由编译生成html文件，生成静态站点,</span><br></pre></td></tr></table></figure>
适合的项目:
    项目所有页面都有做SEO的时候
</code></pre>
<p>SEO优化方案<br>    1、前后端不分离(前端写好模板页面布局，扔给后端就可以了，不方便)<br>        -   不存在接口调用，压力全在后端<br>        -   不对外暴露接口，安全性好</p>
<pre><code>2、前后端分离
    2.1 SPA单页面应用对SEO不友好，数据是后期浏览器访问页面后渲染出来的
        -   压力分散到客户端，用户机器配置
    2.1 vue-cli项目 实现预渲染
        -   某些页面需要SEO的情况适合
    2.3 服务端渲染
        -   整个站点都需要seo
        -   起两个服务，Node server 和 后端接口服务，压力在服务端
</code></pre>
<h3 id="Nuxt"><a href="#Nuxt" class="headerlink" title="Nuxt"></a>Nuxt</h3><p>安装:<a target="_blank" rel="noopener" href="https://nuxtjs.org/docs/get-started/installation#using-create-nuxt-app">Nuxt2</a></p>
<p>目录结构</p>
<ul>
<li>pages           存放页面<ul>
<li>新建页面自动添加到路由，可直接访问</li>
</ul>
</li>
<li>components      存放组件<ul>
<li>config文件 component 为 true 时，下面的组件，其他页面就可以直接引</li>
</ul>
</li>
<li>static          存放静态资源</li>
<li>store           vuex状态树</li>
<li>nuxt.config.js  配置文件</li>
</ul>
<p>概念<br>    路由<code>不需要手动配置</code>，会根据pages目录下的文件自动生成<br>    页面上用到的组件会自动去components目录查找，<code>不需要导入</code> -&gt; 可配置</p>
<h4 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h4><p>服务端生命周期(输出终端打印,里面不能用浏览器相关的对象 如localStorage)</p>
<ol>
<li><code>nuxtServerInit</code> 在 store action 中<ul>
<li>可初始化数据，比如获取token</li>
</ul>
</li>
<li><code>middleware</code>, 全局从 <code>nuxt.config.js</code> 指定，局部重页面组件中指定 要执行的内容<ul>
<li>可验证 token ，类似vue的路由的守卫</li>
</ul>
</li>
<li><code>validate(&#123;params,query&#125;)</code><ul>
<li>校验参数是否正确,不正确 直接重定向到 404 页面</li>
</ul>
</li>
<li><code>asyncData(&#123;$axios,store,params&#125;)</code>, 仅仅页面组件中用(page 下)，页面加载之前调用<ul>
<li>常用于发送请求操作,获取数据     </li>
<li>获取数据 <code>this.List = data</code> 变成 <code>return &#123; List: data &#125;</code></li>
</ul>
</li>
<li><code>fetch(&#123;$axios,app,store,params&#125;)</code>，页面加载前调用<ul>
<li><p>asyncData类似，在<code>组件</code>和<code>页面</code>都能用(渲染页面前会填充页面状态树 store 数据)</p>
</li>
<li><p>建议组件中才使用fetch</p>
<ul>
<li>组件中没有 {$axios,app,store,params} 这些上下文对象，用 this.$axios 代替</li>
</ul>
</li>
<li><p>this.List &#x3D; data;this.存在的，但是拿不到数据，this.data.List &#x3D; data;可能可以拿到？？ </p>
</li>
<li><p>或者fetch页面中是拿来操作store的??</p>
</li>
</ul>
</li>
</ol>
<p>服务端与客户端 共有的 生命周期（控制台 Nuxt SSR 中有，Nuxt SSR 外也有打印，也不能用浏览器相关对象）</p>
<ol>
<li><code>beforeCreate</code> 和 <code>created</code></li>
</ol>
<p>客户端的生命周期（输出仅控制台 Nuxt SSR 外才打印的）</p>
<ol>
<li><code>beforeMount</code> 和 <code>mounted</code></li>
<li><code>beforeUpdate</code> 和 <code>updated</code></li>
<li><code>beforeDestroy</code> 和 <code>destroyed</code></li>
</ol>
<p>持久化存储，使<code>服务端</code>和<code>客服共享</code>的生命周期可以访问持久数据<br>1、安装模块 <code>npm install cookie-universal-nuxt -S</code><br>2、nuxt.config.js -&gt; modules 添加 <code>cookie-universal-nuxt</code><br>3、使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 登入成功的时候,下次不用登录，也可以拿到这个数据，放到store.state中，服务端生命周期就可以通过sotore拿到这个数据</span></span><br><span class="line"><span class="comment">// 代替localStorage.set(&quot;token&quot;,&quot;xxxxx&quot;)</span></span><br><span class="line"><span class="variable language_">this</span>.<span class="property">$cookies</span>.<span class="title function_">set</span>(<span class="string">&quot;token&quot;</span>,<span class="string">&#x27;xxxxx&#x27;</span>)</span><br><span class="line"><span class="comment">// 获取</span></span><br><span class="line"><span class="variable language_">this</span>.<span class="property">$cookies</span>.<span class="title function_">get</span>(<span class="string">&quot;token&quot;</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<h4 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h4><p>1、page 目录下默认生成路由，路由路径，根据目录结构生成<br>2、子路由，如果page有<code>index.vue</code>,那么新建一个<code>同名的文件夹</code>，里面的页面，就是index的子路由<br>3、动态路由，建一个 下划线开头的页面如 <code>_id.vue</code><br>4、重构还想用原来router.js 的话，需要通过插件 <code>@nuxtjs/router</code> 处理<br>    -   npm install @nuxtjs&#x2F;router -S<br>    -   nuxt.config.js ,modules:[“@nuxtjs&#x2F;router”] 配置<br>    -   把自己的 router.js 的懒加载干掉，再文件放到根目录<br>    -   修改一下 export 。。。<br>    -   里面的<code>导航守卫</code>也属于服务端的生命周期,里面操作在终端打印</p>
<p>导航守卫</p>
<ol>
<li>自己定义的路由表，用法和vue一样</li>
<li>nuxt 的导航守卫<ul>
<li>中间件 middleware<ul>
<li>配置文件 添加 router 配置，根文件夹新建 middleware 文件夹，里面存放做的事情</li>
<li>配置文件 设置全局，页面中设置 局部</li>
</ul>
</li>
<li>插件 plugin</li>
</ul>
</li>
</ol>
<p>特点<br>1、无需懒加载</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;nuxt-link to=<span class="string">&quot;/login&quot;</span>&gt;跳转登录页面&lt;/nuxt-link&gt;</span><br></pre></td></tr></table></figure>

<h4 id="nuxt-config-js"><a href="#nuxt-config-js" class="headerlink" title="nuxt.config.js"></a>nuxt.config.js</h4><blockquote>
<p>里面的配置都是全局的</p>
</blockquote>
<ol>
<li><p>head</p>
<ul>
<li>ssr 每个页面如果没设置<code>自己独有的 tdk </code>等信息，就会用全局的</li>
<li>全局hander是一个对象信息，每个页面中的 是一个 head 函数,return出 里面的信息</li>
<li>局部 与 全局相同的属性可以不写,一般 标题 描述 关键字就可以了 <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="title function_">head</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="attr">title</span>: <span class="string">&#x27;页面独有 head 属性设置&#x27;</span>,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>css</p>
<ul>
<li>全局引入：css模块添加 “~&#x2F;static&#x2F;xxx&#x2F;style.css”</li>
<li>局部引入：@import “~&#x2F;static&#x2F;xxx&#x2F;style.css”;</li>
<li>nuxt 中 <code>页面样式</code>如果<code>不写 scoped</code> ,页面间的样式<code>不会相互影响</code>，但是这个样式却会在<code>组件</code>中生效</li>
<li>scss 需要安装 <code>npm install sass sass-loader@10.1.1 -D</code>,只要安装上去就可以了，最新版本好像不能用</li>
</ul>
</li>
<li><p>components</p>
<ul>
<li>设置位 true 后，页面中使用组件就可以不用注册，就能直接使用了</li>
</ul>
</li>
<li><p>plugins</p>
<ul>
<li>呈现页面之前要运行的插件</li>
<li>使用场景 <code>axios二次封装</code>、<code>第三方插件</code>、<code>ElementUi</code> …<ul>
<li><code>~/plugin/xxxelementui.js</code></li>
<li>css部分需要映入 <code>插件相关的css</code></li>
<li>JS 中 再 import Vue 、import Element ， Vue.use(Element) 这些操作</li>
</ul>
</li>
</ul>
</li>
<li><p>modules</p>
<ul>
<li><code>npm install @nuxtjs/axios -S</code> 创建项目如果有选中的话就不用安装了</li>
<li>modules 中添加 ‘@nuxtjs&#x2F;axios’ 配置nuxt内置的axios</li>
<li>接口注意事项：SSR是为了seo优化，所有请求接口一定先在服务端口拿到数据，再打开页面，所以一般都再服务端周期调用</li>
</ul>
</li>
<li><p>axios</p>
<ul>
<li>配置代理</li>
<li>modules 安装并添加 <code>@nuxtjs/axios</code>,<code>@nuxtjs/proxy</code> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">modules</span>: [</span><br><span class="line">         <span class="string">`@nuxtjs/axios`</span>,</span><br><span class="line">         <span class="string">`@nuxtjs/proxy`</span></span><br><span class="line">    ],</span><br><span class="line">    <span class="attr">axios</span>: &#123;</span><br><span class="line">        <span class="comment">// 是否可跨域</span></span><br><span class="line">        <span class="attr">proxy</span>: <span class="literal">true</span>,</span><br><span class="line">        <span class="comment">// 重发次数</span></span><br><span class="line">        <span class="attr">retry</span>: &#123;<span class="attr">retries</span>:<span class="number">5</span>&#125;,</span><br><span class="line">        <span class="comment">// 不同环境下基本地址</span></span><br><span class="line">        <span class="attr">baseURL</span>: <span class="string">&#x27;/&#x27;</span>, <span class="comment">// 开发环境 xxx 否则 xxx</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">proxy</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;/api&#x27;</span>:&#123;</span><br><span class="line">            <span class="attr">target</span>: <span class="string">&#x27;http://localxxxxxx&#x27;</span>,</span><br><span class="line">            <span class="attr">pathRewrite</span>:&#123;</span><br><span class="line">                <span class="string">&#x27;^/api&#x27;</span>:<span class="string">&#x27;&#x27;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>loading</p>
<ul>
<li>nuxt 默认每个页面加载都有一个黑条 <code>loading:false</code> 禁用，自己去axios配置</li>
<li>或更改样式 <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">loading</span>:&#123;</span><br><span class="line">    <span class="attr">color</span>:red</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>或指定loading 动画文件 <code>loading:&#39;~/components/loading.vue&#39;</code> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    <span class="title function_">data</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            <span class="attr">loading</span>: <span class="literal">false</span>,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">methods</span>:&#123;</span><br><span class="line">        <span class="title function_">start</span>(<span class="params"></span>)&#123; <span class="comment">// 路由更新，浏览器地址发送变化时调用</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">loading</span> = <span class="literal">true</span>;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="title function_">finish</span>(<span class="params"></span>)&#123; <span class="comment">// 更新完毕，asyncData 调用完成，且页面完成加载时调用</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="property">loading</span> = <span class="literal">false</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="title function_">fial</span>(<span class="params"></span>)&#123;&#125;,</span><br><span class="line">        <span class="title function_">increase</span>(<span class="params">num</span>)&#123; <span class="comment">// 页面加载过程中调用，num 小于100</span></span><br><span class="line"></span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>server 配置渲染node服务器端口</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server</span>:&#123;</span><br><span class="line">    <span class="attr">prot</span>:<span class="number">3000</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<h4 id="项目上线"><a href="#项目上线" class="headerlink" title="项目上线"></a>项目上线</h4><ol>
<li><code>npm run build</code> 打包</li>
<li>打包好的 <code>.nuxt</code>,<code>static</code>,<code>nuxt.config.js</code>,<code>package.json</code>, 上传到服务器</li>
<li>服务器安装node环境，执行 <code>npm install</code><ul>
<li>安装MongoDB数据库，mongoose 首先 systemctl 运行数据库，设置开机启动</li>
<li>直接启动 或 <code>pm2 start bin/www</code> 启动服务器接口服务</li>
<li><code>npm run start</code> 或 <code>pm2 --name=nuxtName start npm -- run start</code> 启动nuxt服务</li>
</ul>
</li>
<li>在服务器上运行 <code>npm run start</code> 启动项目，创建 <code>localhost:3000</code> 服务</li>
<li>通过nginx将 <code>localhost:3000</code> 代理到需要用的域名 <code>www.xxxx.com</code> 中</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/web/vue/vue-ssr-nuxt/">http://example.com/2023/07/22/web/vue/vue-ssr-nuxt/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/web/vue/vue-ssr-nuxt-2023/" title="nuxt"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">nuxt</div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/web/vue/vue-vue2/" title="Vue基础"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Vue基础</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Nuxt"><span class="toc-number">2.</span> <span class="toc-text">Nuxt</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">2.1.</span> <span class="toc-text">生命周期</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1"><span class="toc-number">2.2.</span> <span class="toc-text">路由</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#nuxt-config-js"><span class="toc-number">2.3.</span> <span class="toc-text">nuxt.config.js</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E4%B8%8A%E7%BA%BF"><span class="toc-number">2.4.</span> <span class="toc-text">项目上线</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>